<script lang="ts" setup>
import { reactive, toRefs, ref, watch } from "vue" // vue
import { getqueryTeamName } from "@/api/SZ/SZXxfy" // 接口
import {
  getSZHdfyApi,
  upSZHdfyApi,
  updateSZHdfyApiIDS,
  delDeSZHdfyApiIDS,
  delDeSZHdfyApi,
  downLoadTable
} from "@/api/SZ/SZHdfy" // 接口
import { FormInstance, ElMessage, ElMessageBox } from "element-plus" // elment
import { Search, Refresh, Finished, Delete, Download } from "@element-plus/icons-vue" // 按钮图标
import { shortcuts, Y, M, D } from "@/utils/dateSet"
import { useRoute } from "vue-router"

import { usePagination } from "@/hooks/usePagination"
// 缓存
defineOptions({
  name: "SZHdfy"
})

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
// 获取路由对象
const route = useRoute()
const data = reactive<any>({
  sums: {},
  searchData: {
    createTime: [
      new Date(Y.value, M.value, D.value, 0, 0, 0).getTime() - 3600 * 1000 * 24 * 1,
      new Date(Y.value, M.value, D.value, 23, 59, 59).getTime()
    ], // 创建时间
    shopId: "", // id店铺
    payFor: undefined, // 旺旺号
    payOrderid: undefined // 外部订单号
  },
  formData: {},
  // 表单验证
  rules: {
    xxx: [{ required: true, trigger: "change", message: "请输入" }]
  }
})

const { searchData, formData, rules, sums } = toRefs(data)
// #region 查
const loading = ref(true)
const tableData = ref<any>([]) //
const tablelist = async () => {
  if (!searchData.value.createTime) {
    searchData.value.createTime = []
  }
  if (!searchData.value.stateTime) {
    searchData.value.stateTime = []
  }
  // 直接访问查询参数
  console.log(route.query.start, route.query.shop, "跳转的参数")
  if (route.query.start) {
    searchData.value.createTime[0] = new Date(Number(route.query.start)).toISOString()
    searchData.value.createTime[1] = new Date(Number(route.query.start)).toISOString()
    searchData.value.shopId = route.query.shop
  }
  // 明细如下
  await getSZHdfyApi({
    ...searchData.value,
    start: new Date(searchData.value.createTime[0]).getTime() || "", // 时间
    end: new Date(searchData.value.createTime[1]).getTime() || "", // 时间
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize
  })
    .then((res: any) => {
      tableData.value = res.data.list
      sums.value = res.data
      loading.value = false
      paginationData.total = res.data.total
    })
    .catch(() => {
      tableData.value = []
    })
}
tablelist()
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
// 搜索
function handleSearch() {
  if (paginationData.currentPage === 1) {
    tablelist()
  }
  paginationData.currentPage = 1
  console.log(searchData.value, "搜索")
}
// 重置
function resetSearch() {
  searchFormRef.value?.resetFields()

  if (paginationData.currentPage === 1) {
    handleSearch()
  }
  paginationData.currentPage = 1
}
// 订单来源根据部门查团队
const queryTeamName = ref()
const TeamName = async () => {
  await getqueryTeamName().then((res: any) => {
    queryTeamName.value = res.data
  })
}
TeamName()
// #endregion

// #region  批量操作
const dataArr = ref<any>([]) // 修改
const dataArrTwo = ref<any>([]) // 删除
const tableRef = ref<any>(null)
// 批量选择
const handleSelectionChange = (val: any) => {
  dataArr.value = []
  dataArrTwo.value = []
  // console.log(val, 1023)
  val.forEach((item: any) => {
    dataArr.value.push(item.id)
    dataArrTwo.value.push(item.clickfarmingreviewId)
  })
}

//批量提交
const addItems = async () => {
  if (dataArr.value == "") {
    ElMessage.error("请选择内容")
  } else {
    updateSZHdfyApiIDS(dataArr.value).then(() => {
      ElMessage.success("批量提交成功")
      tablelist()
    })
  }
}
// 批量撤销
const DeleteItems = async () => {
  if (dataArrTwo.value == "") {
    ElMessage.error("请选择内容")
  } else {
    delDeSZHdfyApiIDS(dataArrTwo.value).then(() => {
      ElMessage.success("批量撤销成功")
      tablelist()
    })
  }
}
// #endregion

// #region 备注弹框
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
// 修改
const handleUpdate = (row: any) => {
  dialogVisible.value = true
  console.log(row, "单个信息")
  formData.value = JSON.parse(JSON.stringify(row)) // 赋值需要深拷贝
}
// 清空form框
const clearValidate = () => {
  formRef.value?.resetFields()
}
// 清空对话框
const resetForm = () => {
  clearValidate()
  formData.value = {}
}
// 确定按钮
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // console.log(formData.value, "确定按钮")
      upSZHdfyApi({
        ...formData.value
      }).then(() => {
        ElMessage.success("反馈")
        dialogVisible.value = false
        tablelist()
      })
    } else {
      return false
    }
  })
}
// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    if (row.clickfarmingreviewId !== null) {
      delDeSZHdfyApi(row.clickfarmingreviewId).then(() => {
        ElMessage.success("删除成功")
        tablelist()
      })
    } else {
      ElMessage.error("请先审核")
    }
  })
}
// #endregion

// #region 下载
const downLoad = () => {
  downLoadTable({
    ...searchData.value,
    start: new Date(searchData.value.createTime[0]).getTime() || "", // 时间
    end: new Date(searchData.value.createTime[1]).getTime() || "" // 时间
  }).then((res: any) => {
    const blob = new Blob([res.data], {
      type: "application/xlsx;charset=utf-8"
    })
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "活动费用.xlsx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
  })
}
// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], tablelist, { immediate: true })
//
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-row justify="center" align="middle">
        <el-col>
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="createTime" label="时间">
              <el-date-picker
                v-model="searchData.createTime"
                type="datetimerange"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                :default-time="defaultTime1"
              />
            </el-form-item>
            <el-form-item prop="shopId" label="店铺">
              <el-select
                v-model.trim="searchData.shopId"
                clearable
                filterable
                placeholder="请选择订单来源"
                style="width: 240px"
              >
                <el-option v-for="item in queryTeamName" :key="item.id" :label="item.name" :value="item.id + ''" />
              </el-select>
            </el-form-item>
            <el-form-item prop="payFor" label="旺旺号">
              <el-input v-model.trim="searchData.payFor" clearable placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="payOrderid" label="外部订单号">
              <el-input v-model.trim="searchData.payOrderid" clearable placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
              <el-button type="primary" :icon="Download" circle @click="downLoad" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <!-- 线下汇总 -->
    <el-card class="top">
      <el-descriptions border :column="4" class="widthsmall" v-loading="loading">
        <el-descriptions-item label="本金合计：" label-align="left" align="center">
          {{ sums.TotalPrincipal }}
        </el-descriptions-item>
        <el-descriptions-item label="佣金合计：" label-align="left" align="center">
          {{ sums.TotalCommission }}</el-descriptions-item
        >
        <el-descriptions-item label="邮费合计：" label-align="left" align="center">
          {{ sums.TotalExpressFee }}</el-descriptions-item
        >
        <el-descriptions-item label="总合计：" label-align="left" align="center">
          {{ sums.Total }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <!-- 刷单明细 -->
    <el-card class="top">
      <div class="mxbox">
        <el-button type="primary" plain>刷单明细</el-button>
        <div class="mxboxRight">
          <el-button type="primary" :icon="Finished" @click="addItems">批量审批</el-button>
          <el-button type="danger" :icon="Delete" @click="DeleteItems">批量撤销</el-button>
        </div>
      </div>
      <el-table :data="tableData" border v-loading="loading" @selection-change="handleSelectionChange" ref="tableRef">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="id" label="id" align="center" />
        <el-table-column prop="manageTime" label="操作时间" align="center" width="160" />
        <el-table-column prop="manageName" label="操作人" align="center" />
        <el-table-column prop="payDt" label="日期" align="center" width="100" />
        <el-table-column prop="payFor" label="旺旺号" align="center" width="120" />
        <el-table-column prop="payOrderid" label="外部订单号" align="center" width="170" />
        <el-table-column prop="payAmount" label="本金" align="center" />
        <el-table-column prop="commission" label="佣金" align="center" />
        <el-table-column prop="expressFee" label="快递费" align="center" />
        <el-table-column prop="largeAmount" label="是否大额" align="center" />
        <el-table-column prop="shopId" label="店铺id" align="center" />
        <el-table-column prop="shopName" label="店铺名称" align="center" width="170" />
        <el-table-column fixed="right" label="审核" align="center" width="150">
          <template #default="scope">
            <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">反馈</el-button>
            <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="clickfarmingreviewId" label="审核id" align="center" />
        <el-table-column prop="clickfarmingTime" label="审核时间" align="center" width="160" />
        <el-table-column prop="clickfarmingreviewName" label="审核人" align="center" />
        <el-table-column prop="resultReview" label="审核备注" align="center" />
        <el-table-column prop="clickfarmingState" label="审核结果" align="center">
          <template #default="scope">
            <el-text v-if="scope.row.clickfarmingState == '1'" class="mx-1" type="success">已审核</el-text>
            <el-text v-if="scope.row.clickfarmingState == '2'" class="mx-1" type="danger">未审核</el-text>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="paginationData.total"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" @close="resetForm">
      <el-form ref="formRef" :rules="rules" :model="formData" style="width: 308px" label-position="left">
        <el-form-item prop="resultReview" label="审核备注">
          <el-input v-model="formData.resultReview" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="clickfarmingState" label="审核结果">
          <el-select
            v-model="formData.clickfarmingState"
            clearable
            filterable
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option :key="1" label="已审核" value="1" />
            <el-option :key="2" label="未审核" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.widthsmall {
  width: 80%;
}
.top {
  margin-top: 20px;
}
.mxbox {
  display: flex;
  justify-content: space-between;
}
.mxboxRight {
  margin-right: 10%;
}
.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}
</style>
